<?php
class controller_LoginController {
    private $view;
    private $args;

    public function setView(View $view) {
        $this->view = $view;
        return $this;
    }

    public function setArgs($args = null) {
        if(null != $args) {
            $this->args = $args;
        }
        return $this;
    }

    public function run() {

        if(empty($this->args['action'])) {
            $this->index();
        } else {
            switch ($this->args['action']) {

                case 'index':
                    $this->index();
                    break;

                case 'logoff':
                    $this->logoff();
                    break;

                default:
                    $this->index();
            }
        }
    }

    public function index() {
        $mapper = new model_UserMapper();
        if(!empty($_POST['login'])) {

            $post = model_ConfigMapper::validate($_POST);
            $model = new model_UserModel();
            $model->setUsername($post['username']);
            $model->setPassword($post['password']);

            $mapper->login($model);

            $this->view->message = $mapper->getMessage();

            if (null == $this->view->message) {
                $user = model_UserMapper::getCurrentUser();
                $this->view->link = '?controller=user&action=index&id='. $user->getId() ;
                $this->view->setRenderTemplate("redirect.phtml");
                return;
            } else {
                $this->view->post = $post;
                $this->view->setRenderTemplate("user/login.phtml");
                return;
            }
        }
        $this->view->setRenderTemplate("user/login.phtml");
    }

    public function logoff() {
        $mapper = new model_UserMapper();
        $mapper->logoff();

        $this->view->setRenderTemplate("redirect.phtml");
        return;

    }
}